const express = require('express');
const router = express.Router();
const { Op } = require('sequelize');
const db = require('../../models');
const { authenticateToken } = require('../../middleware/auth');
const { success, error } = require('../../utils/response');

/**
 * 获取总体统计数据
 * GET /api/stats/overview
 */
router.get('/overview', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    // 基础统计
    const [diaryCount, categoryCount, tagCount, imageCount] = await Promise.all([
      db.Diary.count({ where: { user_id } }),
      db.Category.count({ where: { user_id } }),
      db.Tag.count({ where: { user_id } }),
      db.Image.count({ where: { user_id } })
    ]);

    // 最近30天的日记数量
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const recentDiaryCount = await db.Diary.count({
      where: {
        user_id,
        created_at: {
          [Op.gte]: thirtyDaysAgo
        }
      }
    });

    // 总字数统计（粗略估算）
    const diaries = await db.Diary.findAll({
      where: { user_id },
      attributes: ['content']
    });

    const totalWords = diaries.reduce((total, diary) => {
      // 移除HTML标签并计算字数
      const plainText = diary.content.replace(/<[^>]*>/g, '');
      return total + plainText.length;
    }, 0);

    // 总浏览次数
    const totalViews = await db.Diary.sum('view_count', {
      where: { user_id }
    }) || 0;

    const overview = {
      diary_count: diaryCount,
      category_count: categoryCount,
      tag_count: tagCount,
      image_count: imageCount,
      recent_diary_count: recentDiaryCount,
      total_words: totalWords,
      total_views: totalViews
    };

    return success(res, overview);

  } catch (err) {
    console.error('获取总体统计错误:', err);
    return error(res, '获取总体统计失败', 500);
  }
});

/**
 * 获取日记趋势数据
 * GET /api/stats/diary-trend
 */
router.get('/diary-trend', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;
    const { period = '30d' } = req.query;

    let days;
    switch (period) {
      case '7d':
        days = 7;
        break;
      case '30d':
        days = 30;
        break;
      case '90d':
        days = 90;
        break;
      case '365d':
        days = 365;
        break;
      default:
        days = 30;
    }

    const startDate = new Date();
    startDate.setDate(startDate.getDate() - days);

    // 按日期分组统计日记数量
    const trendData = await db.Diary.findAll({
      where: {
        user_id,
        created_at: {
          [Op.gte]: startDate
        }
      },
      attributes: [
        [db.sequelize.fn('DATE', db.sequelize.col('created_at')), 'date'],
        [db.sequelize.fn('COUNT', db.sequelize.col('id')), 'count']
      ],
      group: [db.sequelize.fn('DATE', db.sequelize.col('created_at'))],
      order: [[db.sequelize.fn('DATE', db.sequelize.col('created_at')), 'ASC']]
    });

    // 填充缺失的日期（补0）
    const result = [];
    for (let i = 0; i < days; i++) {
      const date = new Date();
      date.setDate(date.getDate() - (days - 1 - i));
      const dateStr = date.toISOString().split('T')[0];
      
      const found = trendData.find(item => item.getDataValue('date') === dateStr);
      result.push({
        date: dateStr,
        count: found ? parseInt(found.getDataValue('count')) : 0
      });
    }

    return success(res, {
      period,
      data: result
    });

  } catch (err) {
    console.error('获取日记趋势错误:', err);
    return error(res, '获取日记趋势失败', 500);
  }
});

/**
 * 获取分类统计
 * GET /api/stats/categories
 */
router.get('/categories', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    const categoryStats = await db.Category.findAll({
      where: { user_id },
      attributes: [
        'id',
        'name',
        'color',
        'icon',
        [db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'diary_count']
      ],
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: [],
          required: false
        }
      ],
      group: ['Category.id'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'DESC']]
    });

    // 计算百分比
    const totalDiaries = categoryStats.reduce((sum, cat) => {
      return sum + parseInt(cat.getDataValue('diary_count'));
    }, 0);

    const result = categoryStats.map(cat => {
      const count = parseInt(cat.getDataValue('diary_count'));
      return {
        id: cat.id,
        name: cat.name,
        color: cat.color,
        icon: cat.icon,
        diary_count: count,
        percentage: totalDiaries > 0 ? Math.round((count / totalDiaries) * 100) : 0
      };
    });

    return success(res, result);

  } catch (err) {
    console.error('获取分类统计错误:', err);
    return error(res, '获取分类统计失败', 500);
  }
});

/**
 * 获取写作统计
 * GET /api/stats/writing
 */
router.get('/writing', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;
    const { period = 'month', year, month } = req.query;

    let startDate, endDate;
    const now = new Date();

    if (period === 'month') {
      const targetYear = year ? parseInt(year) : now.getFullYear();
      const targetMonth = month ? parseInt(month) - 1 : now.getMonth();
      startDate = new Date(targetYear, targetMonth, 1);
      endDate = new Date(targetYear, targetMonth + 1, 0);
    } else if (period === 'year') {
      const targetYear = year ? parseInt(year) : now.getFullYear();
      startDate = new Date(targetYear, 0, 1);
      endDate = new Date(targetYear, 11, 31);
    } else {
      // 全部
      startDate = new Date('1970-01-01');
      endDate = now;
    }

    // 按日期分组统计
    const writingStats = await db.Diary.findAll({
      where: {
        user_id,
        diary_date: {
          [Op.between]: [startDate, endDate]
        }
      },
      attributes: [
        [db.sequelize.fn('DATE', db.sequelize.col('diary_date')), 'date'],
        [db.sequelize.fn('COUNT', db.sequelize.col('id')), 'count'],
        [db.sequelize.fn('SUM', db.sequelize.fn('LENGTH', db.sequelize.col('content'))), 'totalWords']
      ],
      group: [db.sequelize.fn('DATE', db.sequelize.col('diary_date'))],
      order: [[db.sequelize.fn('DATE', db.sequelize.col('diary_date')), 'ASC']]
    });

    res.json({
      success: true,
      data: {
        period,
        year: year || now.getFullYear(),
        month: month || (now.getMonth() + 1),
        stats: writingStats.map(stat => ({
          date: stat.getDataValue('date'),
          count: parseInt(stat.getDataValue('count')),
          totalWords: parseInt(stat.getDataValue('totalWords')) || 0
        }))
      }
    });

  } catch (error) {
    console.error('获取写作统计错误:', error);
    res.status(500).json({
      error: '获取写作统计失败'
    });
  }
});

/**
 * 获取心情统计
 * GET /api/stats/mood
 */
router.get('/mood', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    const moodStats = await db.Diary.findAll({
      where: {
        user_id,
        mood: { [Op.ne]: null }
      },
      attributes: [
        'mood',
        [db.sequelize.fn('COUNT', db.sequelize.col('id')), 'count']
      ],
      group: ['mood'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('id')), 'DESC']]
    });

    const total = moodStats.reduce((sum, mood) => sum + parseInt(mood.getDataValue('count')), 0);

    const result = moodStats.map(mood => ({
      mood: mood.mood,
      count: parseInt(mood.getDataValue('count')),
      percentage: total > 0 ? Math.round((parseInt(mood.getDataValue('count')) / total) * 100) : 0
    }));

    res.json({
      success: true,
      data: result
    });

  } catch (error) {
    console.error('获取心情统计错误:', error);
    res.status(500).json({
      error: '获取心情统计失败'
    });
  }
});

/**
 * 获取日历统计
 * GET /api/stats/calendar
 */
router.get('/calendar', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;
    const { year, month } = req.query;
    
    const targetYear = year ? parseInt(year) : new Date().getFullYear();
    const targetMonth = month ? parseInt(month) - 1 : new Date().getMonth();
    
    const startDate = new Date(targetYear, targetMonth, 1);
    const endDate = new Date(targetYear, targetMonth + 1, 0);

    const calendarStats = await db.Diary.findAll({
      where: {
        user_id,
        diary_date: {
          [Op.between]: [startDate, endDate]
        }
      },
      attributes: [
        [db.sequelize.fn('DATE', db.sequelize.col('diary_date')), 'date'],
        [db.sequelize.fn('COUNT', db.sequelize.col('id')), 'count']
      ],
      group: [db.sequelize.fn('DATE', db.sequelize.col('diary_date'))],
      order: [[db.sequelize.fn('DATE', db.sequelize.col('diary_date')), 'ASC']]
    });

    // 生成完整的日历数据
    const calendarData = [];
    const daysInMonth = endDate.getDate();
    
    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(targetYear, targetMonth, day);
      const dateStr = date.toISOString().split('T')[0];
      
      const found = calendarStats.find(stat => stat.getDataValue('date') === dateStr);
      calendarData.push({
        date: dateStr,
        count: found ? parseInt(found.getDataValue('count')) : 0,
        hasEntry: found ? true : false
      });
    }

    res.json({
      success: true,
      data: {
        year: targetYear,
        month: targetMonth + 1,
        calendar: calendarData
      }
    });

  } catch (error) {
    console.error('获取日历统计错误:', error);
    res.status(500).json({
      error: '获取日历统计失败'
    });
  }
});

/**
 * 获取标签云数据
 * GET /api/stats/tag-cloud
 */
router.get('/tag-cloud', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;
    const { limit = 50 } = req.query;

    const tagStats = await db.Tag.findAll({
      where: { user_id },
      attributes: [
        'id',
        'name',
        'color',
        [db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'usage_count']
      ],
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: [],
          required: true // 只返回有使用的标签
        }
      ],
      group: ['Tag.id'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'DESC']],
      limit: parseInt(limit)
    });

    // 计算权重（用于标签云大小）
    const maxCount = tagStats.length > 0 ? parseInt(tagStats[0].getDataValue('usage_count')) : 0;

    const result = tagStats.map(tag => {
      const count = parseInt(tag.getDataValue('usage_count'));
      return {
        id: tag.id,
        name: tag.name,
        color: tag.color,
        usage_count: count,
        weight: maxCount > 0 ? Math.ceil((count / maxCount) * 5) : 1 // 1-5的权重
      };
    });

    return success(res, result);

  } catch (err) {
    console.error('获取标签云错误:', err);
    return error(res, '获取标签云失败', 500);
  }
});

/**
 * 获取心情统计
 * GET /api/stats/moods
 */
router.get('/moods', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    const moodStats = await db.Diary.findAll({
      where: {
        user_id,
        mood: {
          [Op.ne]: null,
          [Op.ne]: ''
        }
      },
      attributes: [
        'mood',
        [db.sequelize.fn('COUNT', db.sequelize.col('id')), 'count']
      ],
      group: ['mood'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('id')), 'DESC']]
    });

    const totalMoods = moodStats.reduce((sum, mood) => {
      return sum + parseInt(mood.getDataValue('count'));
    }, 0);

    const result = moodStats.map(mood => {
      const count = parseInt(mood.getDataValue('count'));
      return {
        mood: mood.mood,
        count,
        percentage: totalMoods > 0 ? Math.round((count / totalMoods) * 100) : 0
      };
    });

    return success(res, result);

  } catch (err) {
    console.error('获取心情统计错误:', err);
    return error(res, '获取心情统计失败', 500);
  }
});

/**
 * 获取天气统计
 * GET /api/stats/weather
 */
router.get('/weather', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    const weatherStats = await db.Diary.findAll({
      where: {
        user_id,
        weather: {
          [Op.ne]: null,
          [Op.ne]: ''
        }
      },
      attributes: [
        'weather',
        [db.sequelize.fn('COUNT', db.sequelize.col('id')), 'count']
      ],
      group: ['weather'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('id')), 'DESC']]
    });

    const totalWeather = weatherStats.reduce((sum, weather) => {
      return sum + parseInt(weather.getDataValue('count'));
    }, 0);

    const result = weatherStats.map(weather => {
      const count = parseInt(weather.getDataValue('count'));
      return {
        weather: weather.weather,
        count,
        percentage: totalWeather > 0 ? Math.round((count / totalWeather) * 100) : 0
      };
    });

    return success(res, result);

  } catch (err) {
    console.error('获取天气统计错误:', err);
    return error(res, '获取天气统计失败', 500);
  }
});

/**
 * 获取写作习惯分析
 * GET /api/stats/writing-habits
 */
router.get('/writing-habits', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    // 按小时统计
    const hourlyStats = await db.Diary.findAll({
      where: { user_id },
      attributes: [
        [db.sequelize.fn('HOUR', db.sequelize.col('created_at')), 'hour'],
        [db.sequelize.fn('COUNT', db.sequelize.col('id')), 'count']
      ],
      group: [db.sequelize.fn('HOUR', db.sequelize.col('created_at'))],
      order: [[db.sequelize.fn('HOUR', db.sequelize.col('created_at')), 'ASC']]
    });

    // 按星期统计
    const weeklyStats = await db.Diary.findAll({
      where: { user_id },
      attributes: [
        [db.sequelize.fn('DAYOFWEEK', db.sequelize.col('created_at')), 'dayofweek'],
        [db.sequelize.fn('COUNT', db.sequelize.col('id')), 'count']
      ],
      group: [db.sequelize.fn('DAYOFWEEK', db.sequelize.col('created_at'))],
      order: [[db.sequelize.fn('DAYOFWEEK', db.sequelize.col('created_at')), 'ASC']]
    });

    // 处理小时数据（补全24小时）
    const hourlyData = Array.from({ length: 24 }, (_, i) => {
      const found = hourlyStats.find(item => parseInt(item.getDataValue('hour')) === i);
      return {
        hour: i,
        count: found ? parseInt(found.getDataValue('count')) : 0
      };
    });

    // 处理星期数据（MySQL的DAYOFWEEK: 1=Sunday, 2=Monday, ..., 7=Saturday）
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const weeklyData = Array.from({ length: 7 }, (_, i) => {
      const found = weeklyStats.find(item => parseInt(item.getDataValue('dayofweek')) === i + 1);
      return {
        day: weekDays[i],
        dayofweek: i + 1,
        count: found ? parseInt(found.getDataValue('count')) : 0
      };
    });

    return success(res, {
      hourly: hourlyData,
      weekly: weeklyData
    });

  } catch (err) {
    console.error('获取写作习惯错误:', err);
    return error(res, '获取写作习惯失败', 500);
  }
});

/**
 * 获取月度统计
 * GET /api/stats/monthly
 */
router.get('/monthly', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;
    const { year = new Date().getFullYear() } = req.query;

    const monthlyStats = await db.Diary.findAll({
      where: {
        user_id,
        [Op.and]: [
          db.sequelize.where(db.sequelize.fn('YEAR', db.sequelize.col('created_at')), year)
        ]
      },
      attributes: [
        [db.sequelize.fn('MONTH', db.sequelize.col('created_at')), 'month'],
        [db.sequelize.fn('COUNT', db.sequelize.col('id')), 'count']
      ],
      group: [db.sequelize.fn('MONTH', db.sequelize.col('created_at'))],
      order: [[db.sequelize.fn('MONTH', db.sequelize.col('created_at')), 'ASC']]
    });

    // 补全12个月的数据
    const monthNames = [
      '1月', '2月', '3月', '4月', '5月', '6月',
      '7月', '8月', '9月', '10月', '11月', '12月'
    ];

    const result = Array.from({ length: 12 }, (_, i) => {
      const found = monthlyStats.find(item => parseInt(item.getDataValue('month')) === i + 1);
      return {
        month: i + 1,
        name: monthNames[i],
        count: found ? parseInt(found.getDataValue('count')) : 0
      };
    });

    return success(res, {
      year: parseInt(year),
      data: result
    });

  } catch (err) {
    console.error('获取月度统计错误:', err);
    return error(res, '获取月度统计失败', 500);
  }
});

module.exports = router; 